package org.psyduck.common.utils;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.psyduck.common.exception.BusinessException;
import org.psyduck.common.model.JsonCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class WebUtils {

    public static String getUserId() {
        return getUserIdFromToken(getToken());
    }

    public static HttpServletRequest getHttpServletRequest(){
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

    private static String getToken(){
        String token = getHttpServletRequest().getHeader(Global.TOKEN_HEADER);
        if(StrUtil.isBlank(token)){
            token = getHttpServletRequest().getParameter("token");
        }
        return token;
    }

	private static String getUserIdFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            if (null == claims) {
                return null;
            }
            return String.valueOf(claims.get(Global.CLAIM_KEY_USER_ID));
        } catch (Exception e) {
            return "";
        }
    }

    private static Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(Global.JWT_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch(ExpiredJwtException e) {
            return null;
        } catch (Exception e) {
            throw new BusinessException(JsonCode.JWT_GET_CLAIMS_ERROR,e.getMessage());
        }
    }

    public static String getContextUrl() {
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
    }

    public static String getUeditorPrefix(){
        if(Global.UPLOAD_TYPE.equals("oss")){
            return Global.OSS_TRANSPORT_PROTOCOL + "://" + Global.OSS_BUCKET_NAME + "." + Global.OSS_ENDPOINT + "/";
        }
        return getContextUrl();
    }

}